import 'dart:async';
import 'dart:io';

import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/OssUpload.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class UserInfoController extends BaseController {
  String nickname = AppData.nickname!;

  String avatar = AppData.avatar!;

  String uid = AppData.uid!;

  late List<AssetEntity>? headImage = [];

  String phoneNumber = AppData.phoneNumber!;

  String encodePhoneNumber = Tools.encryptPhoneNumber(AppData.phoneNumber!);

  //验证码输入框
  TextEditingController vertifyTxtCtr = TextEditingController();

  ///新手机号的输入框
  TextEditingController newPhoneTxt = TextEditingController();

  int countdown = 0; //倒计时数字
  String countdownTxt = '获取验证码'; //倒计时的文本

  //当前步骤
  int step = 1;

  //验证码按钮颜色
  Color buttonColor = ThemeConfig.themeColor;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
  }

  //修改昵称
  void updateName(String tag) {
    // print('asdasd123214'+nickname+","+nickname.trim());
    if (nickname.trim().isNotEmpty) {
      Map<String, dynamic> map = {};
      map['nickname'] = nickname;
      Network.updateUserInfo(map).then((value) {
        if (value == true) {
          AppData.nickname = nickname;
          SmartDialog.dismiss(tag: tag);
          Tools.showToast("昵称修改成功");
          Tools.hideLoading();
          update();
        }
      }).catchError((onError) {
        Tools.hideLoading();
      });
    } else {
      Tools.showToast('请输入不包含特殊字符的昵称!');
    }
  }

  //修改头像
  Future<void> saveImage() async {
    if (headImage == null || headImage!.isEmpty) {
      Tools.showToast('没有头像可传');
      Tools.hideLoading();
      return;
    }

    Tools.showLoading(); // 在开始时显示加载

    try {
      List<File> fileList = [];

      // 使用for循环来保证异步操作顺序执行
      for (var element in headImage!) {
        File? file = await element.file;
        if (file != null) {
          fileList.add(file);
        }
      }

      // 上传文件
      List<String>? data = await OssUpload.upoladFiles(fileList);

      if (data != null && data.isNotEmpty) {
        avatar = data[0]; // 获取第一个上传的头像链接

        if (avatar.isNotEmpty) {
          Map<String, dynamic> map = {'avatar': avatar};

          // 更新用户信息
          bool updateSuccess = await Network.updateUserInfo(map);

          if (updateSuccess) {
            AppData.avatar = avatar;
            Tools.showToast("头像修改成功");
            update(); // 刷新页面
          } else {
            Tools.showToast("头像修改失败");
          }
        }
      } else {
        Tools.showToast("文件上传失败");
      }
    } catch (e) {
      Tools.showToast("发生错误: $e");
      print("保存头像时发生错误: $e");
    } finally {
      Tools.hideLoading(); // 无论成功或失败，都应该隐藏加载动画
      Get.back(); // 关闭当前页面
    }
  }

  Timer? timer;
  //接收旧手机号的验证码
  void sendVerfityCode() {
    if (step == 2) {
      if (newPhoneTxt.text == '') {
        Tools.showToast("请先填写手机号");
        return;
      }
    }
    print(countdown);
    if (countdown == 0) {
      countdown = 60;
      if (step == 1) {
        Network.editMobileVerifyCode(); //获取老手机的验证码
      } else {
        Network.editNewMobileVerifyCode(newPhoneTxt.text); //获取新手机的验证码
      }

      timer = Timer.periodic(Duration(seconds: 1), (timer) {
        countdown--;
        countdownTxt = "重发(${countdown.toString()})";
        buttonColor = Tools.fromHex("#D7D7D7");
        if (countdown == 0) {
          countdownTxt = '重新发送';
          buttonColor = ThemeConfig.themeColor;
          timer.cancel();
        }
        update();
      });
    }
  }

  //修改手机号下一步及提交
  void submit() {
    if (step == 1) {
      if (vertifyTxtCtr.text == '') {
        Tools.showToast("请先输入验证码");
        return;
      }

      //旧手机验证
      Network.checkVerifyCode(AppData.phoneNumber!, vertifyTxtCtr.text).then((value) {
        if (value) {
          vertifyTxtCtr.text = ''; //重置验证码输入框
          step = 2; //进入步骤2
          if (timer != null) {
            timer!.cancel();
            countdown = 0;
            countdownTxt = "获取验证码";
            buttonColor = ThemeConfig.themeColor;
          }
          update();
        }
      });
    } else {
      if (newPhoneTxt.text == '') {
        Tools.showToast("手机号不能为空");
        return;
      }

      if (vertifyTxtCtr.text == '') {
        Tools.showToast("验证码不能为空");
        return;
      }
      print("新手机提交");
      //新手机提交
      Network.editMobile(newPhoneTxt.text, vertifyTxtCtr.text).then((value) {
        if (value) {
          AppData.phoneNumber = newPhoneTxt.text; //更新缓存
          Tools.showToast("修改成功");
          Get.offNamed(Routes.setting);
        }
      });
    }
  }

  @override
  void onClose() {
    if (timer != null) {
      timer!.cancel();
    }
    super.onClose();
  }
}
